<template>
  <div class="task-details-page">
    <!-- 顶部导航栏 -->
    <div class="breadcrumb">
      <button @click="goBack()">返回</button>
    </div>

    <!-- 任务信息模块 -->
    <div class="task-info card">
      <h3>任务信息</h3>
      <div  class="grid grid-cols-3 gap-4" >
        <div v-if="taskInfo">名称：{{ taskInfo.name}}</div>
        <div v-if="taskInfo">UID：{{taskInfo.uid}}</div>
        <div v-if="taskInfo.status">任务依赖：{{taskInfo.spec.parents}}</div>
        <div v-if="taskInfo.status">创建时间：{{taskInfo.status.start}}</div>
        <div v-if="taskInfo.spec">已存在时间：{{runningTime}}</div>
        <div v-if="taskInfo.spec">资源需求：    <p v-for="(resource, index) in taskInfo.spec.resource_requirements" :key="index">
            名称：{{ resource.name }}  需求数量：[{{resource.lowbound}}-{{resource.upperbound}}]
          </p> 
        </div>
        <div>调度策略：副本部署，优先级 10，QoS XX</div>
        <!-- <div v-if="taskInfo.spec">
          部署方式：
          <a  v-for="(value,index) in taskInfo.spec.actions" :key="index" href={{value.spec.runtimes[0].image}} target="_blank">
          {{ value.spec.runtimes[0].type +" " + value.spec.runtimes[0].image}}
          </a>
        </div> -->
      </div>
    </div>

    <!-- 任务状态模块 -->
    <div class="task-status card">
      <h3>任务状态</h3>
      <div class="grid grid-cols-3 gap-4">
        <div v-if="taskInfo.status">运行节点：{{taskInfo.status.node}}</div>
        <div v-if="taskInfo.status">执行状态：{{taskInfo.status.phase}}</div>
        <div v-if="taskInfo.status">最近更新时间：{{taskInfo.status.last_time}}</div>
        <div>已运行时间：{{runningTime}}</div>
        <div>任务进程:PID 1000</div>
        <div>任务输入:Path XXX</div>
        <div>任务输出:Model XXX.pt</div>
        <div>
          访问方式：
          <a href="mem://xxx/xxx/xxx.pt" target="_blank">mem://xxx/xxx/xxx.pt</a>
        </div>
      </div>
      <!-- CPU 和内存使用折线图 -->
      <div class="charts flex">
        <div id="cpu-usage-chart" class="chart"></div>
        <div id="memory-usage-chart" class="chart"></div>
      </div>
    </div>

    <!-- 事件日志模块 -->
    <div class="event-logs card">
      <h3>事件日志</h3>
      <div class="filter-bar">
        <p>事件等级：</p>
        <select v-model="logLevelFilter" class="filter-select">
          <option value="ALL">所有等级</option>
          <option value="INFO">INFO</option>
          <option value="ERROR">ERROR</option>
        </select>
        <p>事件类型：</p>
        <select v-model="logTypeFilter" class="filter-select">
          <option value="ALL">所有类型</option>
          <option value="任务创建">任务创建</option>
          <option value="任务部署">任务部署</option>
        </select>
      </div>
      <table class="log-table">
        <thead>
          <tr>
            <th>事件 ID</th>
            <th>事件等级</th>
            <th>事件代码</th>
            <th>事件类型</th>
            <th>发生时间</th>
            <th>描述信息</th>
          </tr>
        </thead>
        <tbody v-if="taskLogs">
          <tr v-for="log in taskLogs.items" :key="log.id">
            <td>{{ log.uid }}</td>
            <td>{{ log.Type }}</td>
            <td>{{ log.count }}</td>
            <td>{{ log.kind }}</td>
            <td>{{ log.EventTime }}</td>
            <td>{{ log.Message }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script  lang="ts">
import { ref, computed, onMounted } from 'vue';
import * as echarts from 'echarts';
import { useRouter } from 'vue-router';
import OpenAPIClientAxios from 'openapi-client-axios';

const api = new OpenAPIClientAxios({
    definition:"http://clusters.luo980.com:11004/apidocs.json",
    axiosConfigDefaults: {
      baseURL: 'http://clusters.luo980.com:11004'
    }
  })



  export default {
    setup() {
      const taskInfo = ref([]);
      const taskLogs = ref([]);
      const route = useRouter();
      const runningTime = ref("")
      let interval:any = null
      onMounted(async() => {
        const client = await api.init();
        const cpuChart = echarts.init(document.getElementById('cpu-usage-chart')!);
        const memoryChart = echarts.init(document.getElementById('memory-usage-chart')!);
        
        const options = {
          xAxis: { type: 'category', data: ['1m', '2m', '3m', '4m', '5m'] },
          yAxis: { type: 'value' },
          series: [{ data: [30, 50, 45, 60, 40], type: 'line' }],
        };

        cpuChart.setOption({ ...options, title: { text: 'CPU 使用' } });
        memoryChart.setOption({ ...options, title: { text: '内存使用' } });

        let taskname = "";
        
        console.log("route:", route);
        console.log("route.currentRoute:", route.currentRoute);
        console.log("route.currentRoute.value:", route.currentRoute.value);
        console.log("route.currentRoute.value.query:", route.currentRoute.value.query);
        
        // 用 router.push 跳转, 用 query 带参数 name=lin
        if (route.currentRoute.value.query.taskName) {
          taskname = route.currentRoute.value.query.taskName;
        }
        console.log(taskname);
        // 向后端发送请求
        
              // 设置定时器，每 3 秒刷新一次数据
        interval = setInterval(async () => {
          try {
            const response = await client['Get group']({"Namespace":"test","Name":taskname})
            const logresponse = await client['Get event']({"Namespace":"test","Name":taskname})
            if (response.status === 200) {
                taskInfo.value = response.data; // 确保使用 .value 来更新 ref
                
                console.log(taskInfo.value)
                runningTime.value = calculateTimeDifference(taskInfo.value.status.start,taskInfo.value.status.last_time)
                console.log(runningTime.value)
            }
            if(logresponse.status === 200){
              console.log(3333333333333333333333333);
              console.log(logresponse.data)
              taskLogs.value = logresponse.data
            }
          } catch (error) {
            console.error('Error:', error);
          }
        }, 3000);

      });
      
      onBeforeUnmount(() => {
        // 组件销毁前清除定时器
        if (interval) {
          clearInterval(interval);
        }
      });
      function calculateTimeDifference(timestamp1: string, timestamp2: string): string {
          // 将字符串转换为日期对象
          const date1: Date = new Date(timestamp1);
          const date2: Date = new Date(timestamp2);

          // 计算时间差（毫秒）
          const timeDifference: number = date2.getTime() - date1.getTime();

          // 将毫秒转换为秒
          const totalSeconds: number = Math.floor(timeDifference / 1000);

          // 将秒转换为分钟和秒
          const minutes: number = Math.floor(totalSeconds / 60);
          const seconds: number = totalSeconds % 60;

          // 返回格式化的字符串
          return `${minutes} min${seconds} s`;
      }   
      const goBack = () => {
        // route.push({path:'./task'})
        route.go(-1)
      };

      // 返回 taskInfo，使其在模板中可用
      return {
        taskInfo,
        goBack,
        runningTime,
        taskLogs
      };
    },
  };


// 示例数据
const taskLogs = ref([
  {
    id: 'Event-2024-11-08-TaskX-Info',
    level: 'INFO',
    code: '0001',
    type: '任务创建',
    time: '2024-11-18 09:47:00',
    description: '任务创建完成，调度到节点 XX',
    solution: '-',
  },
  {
    id: 'Event-2024-11-08-TaskX-Error',
    level: 'ERROR',
    code: '1001',
    type: '任务部署',
    time: '2024-11-18 09:48:05',
    description: '任务部署过程中发生错误',
    solution: 'Restart',
  },
]);

const logLevelFilter = ref('');
const logTypeFilter = ref('');

// 过滤日志
const filteredLogs = computed(() =>
  taskLogs.value.filter(
    (log) =>
      (!logLevelFilter.value || log.level === logLevelFilter.value) &&
      (!logTypeFilter.value || log.type === logTypeFilter.value)
  )
);




</script>

<style scoped>
.card {
  border: 1px solid #ddd;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 8px;
  background: #fff;
}
.charts {
  display: flex;
  gap: 16px;
  margin-top: 16px;
}
.chart {
  width: 50%;
  height: 200px;
}
.log-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 16px;
}
.log-table th,
.log-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
.filter-bar {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}
.filter-select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>
